package com.tyl.xtk.controller;

import com.tyl.xtk.beans.po.User;
import com.tyl.xtk.beans.query.LoginForm;
import com.tyl.xtk.beans.vo.LoginResult;
import com.tyl.xtk.beans.vo.Result;
import com.tyl.xtk.config.validation.groups.Insert;
import com.tyl.xtk.service.UserService;
import com.wf.captcha.base.Captcha;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.groups.Default;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.UUID;

/**
 * create by tyl at 2025/8/27
 */
@RestController
@Tag(name = "登录相关")
public class LoginController {

    @Resource
    UserService userService;

    // 使用 SpecCaptcha 确保能调用 text() 和 next() 方法，保证图文一致性
    @Resource
    private Captcha captcha;

    @PostMapping("login")
    @Operation(summary = "登录")
    public Result<LoginResult> login(@RequestBody @Validated LoginForm loginForm) {
        return userService.login(loginForm);
    }

    @PostMapping("logout")
    @Operation(summary = "退出登录")
    public Result<String> logout() {
        boolean r = userService.logout();
        if (!r) {
            return Result.fail("退出登录失败");
        }
        return Result.success("退出登录成功");
    }

    @GetMapping("me")
    @Operation(summary = "获取登录用户的信息")
    public Result<User> me() {
        User user = userService.selectCurrentUser();
        return Result.success(user);
    }

    @PostMapping("register")
    @Operation(summary = "用户注册")
    public Result<User> register(@RequestBody @Validated({Insert.class, Default.class}) User user) {
        return userService.register(user);
    }

    @GetMapping("/captcha")
    @Operation(summary = "获取验证码")
    public Result<String> captcha() {
        // 生成唯一标识符
        String uuid = UUID.randomUUID().toString();

        // 获取验证码文本（必须先获取文本，才能保证 out 输出的是对应的图）
        String captchaText = captcha.text();

        // 将验证码文本存储到Redis中，设置5分钟过期时间
        userService.saveCaptchaToRedis(uuid, captchaText);

        // 创建输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 使用 out 方法直接将验证码图片写入输出流
        captcha.out(baos);

        // 将图片转换为Base64编码
        byte[] imageBytes = baos.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        // 返回UUID和Base64编码的图片
        return Result.success(uuid + "," + base64Image);
    }
}